package com.kornero.auto.util.email;

import com.kornero.auto.entities.Car;
import com.kornero.auto.util.Threads;
import com.sun.mail.smtp.SMTPSendFailedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    // SMTP-server address.
    private static final String SMTP_HOST = "smtp.mail.ru";

    // SMTP-server port.
    private static final int SMTP_PORT = 25;
    private static final int TIMEOUT = 1500;

    public static synchronized void sendCarOnEmail(final Car car, final String emailTo) {
        final String subject = "Model: " + car.getModel() + ", year: " + car.getYear()
                + ", price: " + car.getPrice() + ", city: " + car.getCity();
        final String text = car.getLink().toString();

        final Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
//        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);

        final Email emailFrom = EmailProvider.getNextEmail();
        final Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailFrom.getSmtpUserName(),
                                emailFrom.getSmtpUserPass());
                    }
                });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(emailFrom.getSmtpUserName()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
            message.setSubject(subject);
            message.setText(text);
            Transport.send(message);
            Threads.sleep(TIMEOUT);
        } catch (SMTPSendFailedException e) {
            if (e.getReturnCode() == EmailErrorCodes.RATE_LIMIT_EXCEEDED.getErrorCode()) {
                logger.warn("sendCar(): Can't send email: server thinks that we are sending spam."
                        + "\n\t EmailTo: " + emailTo
                        + "\n\t EmailFrom: " + emailFrom
                        + "\n\t Car: " + car);
            } else {
                logger.error("sendCar(): Can't send email."
                        + "\n\t EmailTo: " + emailTo
                        + "\n\t Car: ", e);
            }
        } catch (MessagingException e) {
            logger.error("sendCar(): Can't send email."
                    + "\n\t EmailTo: " + emailTo
                    + "\n\t Car: ", e);
        }
    }
}
